package com.ruoyi.web.controller.kujiale;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.JYXResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.PmMaterialItem;
import com.ruoyi.system.domain.PmMaterialList;
import com.ruoyi.system.domain.vo.BudgetGroupVo;
import com.ruoyi.system.domain.vo.EnumAggregationVo;
import com.ruoyi.system.service.IEnumService;
import com.ruoyi.system.service.IPmMaterialItemService;
import com.ruoyi.system.service.IPmMaterialListService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/project/material")
@Api(tags = "项目物料管理接口（关联t_project）")
public class PmMaterialController extends BaseController {


    @Autowired
    private IPmMaterialListService materialListService;

    @Autowired
    private IPmMaterialItemService materialItemService;

    @Autowired
    private IEnumService enumService;


    /**
     * 分页查询物料清单列表
     */
    @ApiOperation("分页查询物料清单（关联项目）")
//    @PreAuthorize("@ss.hasPermi('project:material:list')")
    @GetMapping("/list")
    public JYXResult list(
            @ApiParam("页码") @RequestParam(defaultValue = "1") int pageNum,
            @ApiParam("每页条数") @RequestParam(defaultValue = "10") int pageSize,
            PmMaterialList list
    ) {
        IPage<PmMaterialList> page = materialListService.selectMaterialListPage(pageNum, pageSize, list);
        return JYXResult.success(page);
    }


    /**
     * 创建物料清单（关联t_project）
     */
    @ApiOperation("创建物料清单（自动关联项目信息）")
//    @PreAuthorize("@ss.hasPermi('project:material:add')")
    @Log(title = "物料清单", businessType = BusinessType.INSERT)
    @PostMapping("/create")
    public AjaxResult create(@RequestBody PmMaterialList list) {
        return toAjax(materialListService.createMaterialList(list) ? 1 : 0);
    }



    /**
     * 修改物料清单基本信息
     */
    @ApiOperation("修改物料清单（名称、业主预算、备注等）")
//    @PreAuthorize("@ss.hasPermi('project:material:edit')")
    @Log(title = "物料清单", businessType = BusinessType.UPDATE)
    @PutMapping("/update")
    public JYXResult updateMaterialList(
            @ApiParam("物料清单信息（必须包含id）") @RequestBody PmMaterialList list
    ) {
        // 获取当前操作人信息（若依框架工具类）
        Long operatorId = SecurityUtils.getUserId();
        String operatorName = SecurityUtils.getUsername();
        boolean result = materialListService.updateMaterialList(list, operatorId, operatorName);
        return result ? JYXResult.success() : JYXResult.error();
    }


    /**
     * 推送清单给业主
     */
    @ApiOperation("推送清单给业主")
    @PreAuthorize("@ss.hasPermi('project:material:push')")
    @Log(title = "物料清单", businessType = BusinessType.UPDATE)
    @PostMapping("/push/{listId}")
    public AjaxResult push(
            @ApiParam("清单ID") @PathVariable Long listId
    ) {
        return toAjax(materialListService.pushToOwner(listId, getUserId(), getUsername()) ? 1 : 0);
    }

    /**
     * 撤回业主推送
     */
    @ApiOperation("撤回业主推送")
    @PreAuthorize("@ss.hasPermi('project:material:cancel')")
    @Log(title = "物料清单", businessType = BusinessType.UPDATE)
    @PostMapping("/cancel/{listId}")
    public AjaxResult cancel(
            @ApiParam("清单ID") @PathVariable Long listId
    ) {
        return toAjax(materialListService.cancelPush(listId, getUserId(), getUsername()) ? 1 : 0);
    }

    /**
     * 分页查询清单下的物料条目
     */
    @ApiOperation("分页查询清单物料条目")
//    @PreAuthorize("@ss.hasPermi('project:material:itemList')")
    @GetMapping("/item/list/{listId}")
    public AjaxResult itemList(
            @ApiParam("清单ID") @PathVariable Long listId,
            @ApiParam("页码") @RequestParam(defaultValue = "1") int pageNum,
            @ApiParam("每页条数") @RequestParam(defaultValue = "10") int pageSize,
            PmMaterialItem item
    ) {
        IPage<PmMaterialItem> page = materialItemService.selectMaterialItemPage(pageNum, pageSize, listId, item);
        return AjaxResult.success(page);
    }

    /**
     * 批量添加物料条目
     */
    @ApiOperation("批量添加物料条目（支持分组）")
//    @PreAuthorize("@ss.hasPermi('project:material:itemAdd')")
    @Log(title = "物料条目", businessType = BusinessType.INSERT)
    @PostMapping("/item/batchAdd/{listId}")
    public AjaxResult batchAddItems(
            @ApiParam("清单ID") @PathVariable Long listId,
            @ApiParam("物料条目列表") @RequestBody List<PmMaterialItem> items
    ) {
        return toAjax(materialItemService.batchAddItems(listId, items) ? 1 : 0);
    }

    /**
     * 确认物料预算类别
     */
    @ApiOperation("确认物料预算类别（同组单选）")
//    @PreAuthorize("@ss.hasPermi('project:material:confirm')")
    @Log(title = "物料条目", businessType = BusinessType.UPDATE)
    @PostMapping("/item/confirm/{itemId}")
    public AjaxResult confirmBudgetType(
            @ApiParam("物料条目ID") @PathVariable Long itemId,
            @ApiParam("最终预算类别（1=基础项，2=升级项，3=增项）") @RequestParam Integer finalBudgetType
    ) {
        return toAjax(materialItemService.confirmBudgetType(itemId, finalBudgetType, getUserId(), getUsername()) ? 1 : 0);
    }

    /**
     * 查询预算分组聚合数据（前端展示用）
     */
    @ApiOperation("查询预算分组聚合数据（按组展示，包含物料分类信息）")
//    @PreAuthorize("@ss.hasPermi('project:material:groupList')")
    @GetMapping("/item/groupList/{listId}")
    public AjaxResult getBudgetGroupList(
            @ApiParam("清单ID") @PathVariable Long listId
    ) {
        List<BudgetGroupVo> groupList = materialItemService.getBudgetGroupListByListId(listId);
        return AjaxResult.success(groupList);
    }

    /**
     * 查询预算分组聚合数据（按物料分类拆分）
     */
    @ApiOperation("查询预算分组聚合数据（按物料分类拆分）")
//    @PreAuthorize("@ss.hasPermi('project:material:groupList')")
    @GetMapping("/item/groupList/categorySplit/{listId}")
    public AjaxResult getBudgetGroupListWithCategorySplit(
            @ApiParam("清单ID") @PathVariable Long listId
    ) {
        Map<Integer, List<BudgetGroupVo>> categoryGroups = materialItemService.getBudgetGroupListByListIdWithCategorySplit(listId);
        return AjaxResult.success(categoryGroups);
    }


    /**
     * 更新物料条目
     */
    @ApiOperation("更新物料条目信息")
//    @PreAuthorize("@ss.hasPermi('project:material:itemUpdate')")
    @Log(title = "物料条目", businessType = BusinessType.UPDATE)
    @PutMapping("/item/update")
    public AjaxResult updateMaterialItem(@RequestBody PmMaterialItem item) {
        return toAjax(materialItemService.updateMaterialItem(item, getUserId(), getUsername()) ? 1 : 0);
    }

    /**
     * 删除物料条目
     */
    @ApiOperation("删除物料条目（逻辑删除）")
//    @PreAuthorize("@ss.hasPermi('project:material:itemDelete')")
    @Log(title = "物料条目", businessType = BusinessType.DELETE)
    @DeleteMapping("/item/delete/{itemId}")
    public AjaxResult deleteMaterialItem(
            @ApiParam("物料条目ID") @PathVariable Long itemId
    ) {
        return toAjax(materialItemService.deleteMaterialItem(itemId, getUserId(), getUsername()) ? 1 : 0);
    }

    /**
     * 批量删除物料条目
     */
    @ApiOperation("批量删除物料条目（逻辑删除）")
//    @PreAuthorize("@ss.hasPermi('project:material:itemBatchDelete')")
    @Log(title = "物料条目", businessType = BusinessType.DELETE)
    @DeleteMapping("/item/batchDelete")
    public AjaxResult batchDeleteMaterialItems(
            @ApiParam("物料条目ID列表") @RequestBody List<Long> itemIds
    ) {
        return toAjax(materialItemService.batchDeleteMaterialItems(itemIds, getUserId(), getUsername()) ? 1 : 0);
    }

    /**
     * 获取所有物料相关枚举（供前端下拉框/状态展示使用）
     */
    @GetMapping("/materialEnums")
    @ApiOperation(
            value = "获取所有物料相关枚举",
            notes = "返回物料管理中所有业务枚举（使用单位、物料分类、预算类别等），包含code和desc，用于前端下拉选择和状态展示",
            response = EnumAggregationVo.class
    )
    public AjaxResult getAllMaterialEnums() {
        EnumAggregationVo enums = enumService.getAllMaterialEnums();
        return AjaxResult.success("获取枚举数据成功", enums);
    }
}
